/**
 * 
 */
package org.zgstudio.ddlchecker;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Iterator;
import java.util.logging.Logger;

/**
 * @author zhguo
 *
 */
class LinkCheckUtil implements Runnable {
    private static Logger logger = Logger.getLogger(LinkCheckUtil.class
                                         .getName());

    private LinkCheckTask task;
    private LinkCheck linkCheck;

    public LinkCheckUtil(LinkCheckTask task, LinkCheck linkCheck) {
        this.task = task;
        this.linkCheck = linkCheck;
    }

    public void run() {
        checkLink();
    }

    public void checkLink() {
        Iterator<Link> it = task.getUrlsInTask().iterator();
        int tries = 0;
        while (it.hasNext()) {
            LinkCheckResult result = new LinkCheckResult();

            Link link = it.next();
            result.setLinkChecked(link);
            result.setCheckTime(new Date());

            URL url = link.getUrl();
            tries = 0;
            try {
                URLConnection connection = url.openConnection();
                if (connection instanceof HttpURLConnection) {
                    HttpURLConnection httpConn = (HttpURLConnection) connection;
                    httpConn.setInstanceFollowRedirects(true);
                    while (tries < 3) {
                        httpConn.connect();
                        httpConn.disconnect();
                        if (httpConn.getResponseCode() >= 300
                                && httpConn.getResponseCode() < 400) {
                            result.setResultCode(ResultCode.REDIRECT);
                            break;
                        } else if (httpConn.getResponseCode() >= 200
                                && httpConn.getResponseCode() < 300) {
                            result.setResultCode(ResultCode.SUCCEED);
                            break;
                        }  else
                            result.setResultCode(ResultCode.FAILED);
                        ++tries;
                    }
                } else {
                    logger.severe("Unrecognized protocol in URL " + url);
                    result.setResultCode(ResultCode.UNRECOG_PROTO);
                }
                result.setCompletionTime(new Date());
            } catch (IOException e) {
                result.setCompletionTime(new Date());
                result.setResultCode(ResultCode.FAILED);
            } finally {
                ResultChecker.getInstance().addNewResult(result);
            }
        }
        ((SimpleLinkCheck)this.linkCheck).notifyComplete();
    }
}
